<template>
  <div style="background: #fff; padding: 30px">
    <div class="Title">账号管理</div>
    <div class="flewbtn">
      <el-button size="large" type="primary" @click="buildUser">创建账号</el-button>
    </div>
    <!-- 展示和编辑表格 -->
    <el-scrollbar style="margin-bottom: 20px" height="700px">
      <el-table
        :data="filterTableData"
        :header-cell-style="{
          'text-align': 'center',
          background: '#f2f3f5',
          height: '50px',
          color: '#000000',
          'font-size': '15px',
        }"
        :cell-style="{ 'text-align': 'center', height: '80px' }"
        style="width: 100%"
        ref="multipleTableRef"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="执行人名称" prop="siteName" />
        <el-table-column label="用户名" prop="users" />
        <el-table-column label="密码" prop="password" />
        <el-table-column label="状态" prop="state" />
        <el-table-column align="right">
          <!-- <template #header>
		        <el-input v-model="search" size="small" placeholder="Type to search" />
		      </template> -->
          <template #header>
            <div>操作</div>
          </template>
          <template #default="scope">
            <!-- <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
            <el-button
              size="small"
              @click="handleEdit(scope.$index, scope.row)"
              type="primary"
              text
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-scrollbar>
    <!-- 分页显示 -->
    <el-pagination
      v-model:current-page="currentPage4"
      v-model:page-size="pageSize4"
      background
      :page-size="20" 
      :small="small"
      :disabled="disabled"
      layout="total, prev, pager, next"
      :total="state.listTotal"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      style="display: flex; justify-content: flex-end"
    />

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="state.showModel"
      title="编辑项目"
      width="500px"
      align-center
      style="font-weight: 600"
    >
      <el-scrollbar height="400px">
        <div style="display: flex; margin-top: 20px; margin-bottom: 20px">
          <div class="userType">账号类型</div>
          <div class="userType_a">
            <el-checkbox-group v-model="state.siteVest" max="1" fill="#409eff" @change="changeSel">
              <el-checkbox label="管理员账号" name="siteVest" />
              <el-checkbox label="普通账号" name="siteVest" />
              <!-- <el-checkbox label="客户运营账号" name="siteVest" /> -->
            </el-checkbox-group>
          </div>
        </div>
        <div style="display: flex; margin-top: 15px; margin-bottom: 18px">
          <div style="margin: 10px 18px 10px 20px; font-weight: 600">账号状态</div>
          <el-radio-group fill="#409eff" v-model="state.radioState" @change="changeStaus" size="small">
            <el-radio-button label="启用" />
            <el-radio-button label="停用" />
          </el-radio-group>
        </div>
        <div style="display: flex; justify-content: center; align-items: center">
          <div class="carryName">
            执行人姓名
          </div>
          <el-input
            v-model="state.name"
            maxlength="15"
            size="small"
            style="flex: 8"
            class="enterpriseName"
          />
        </div>

        <div class="carryName_a">
          <div class="carryName_b">
            手机号
          </div>
          <el-input
            v-model="state.phone"
            maxlength="15"
            size="small"
            style="flex: 8"
            class="enterpriseName"
          />
        </div>
        <div class="bankNum">
          <div class="bankNum_a">
            账号
          </div>
          <el-input
            v-model="state.username"
            maxlength="15"
            size="small"
            style="flex: 8"
            class="enterpriseName"
          />
        </div>
        <div class="passW">
          <div class="passW_a">
            密码
          </div>
          <el-input
            v-model="state.password"
            maxlength="15"
            size="small"
            style="flex: 8"
            class="enterpriseName"
          />
        </div>
        <!-- <div class="passW_b">
          <div style="flex: 2; line-height: 20px; text-align: center; font-weight: 600">
            确认密码
          </div>
          <el-input
            v-model="state.inputVal"
            size="small"
            style="flex: 8"
            class="enterpriseName"
          />
        </div>
        <div style="display: flex; margin-top: 15px; margin-bottom: 25px">
          <div style="margin: 10px 18px 10px 16px; font-weight: 600">路线状态</div>
          <el-radio-group fill="#409eff" v-model="state.radioState" size="small">
            <el-radio-button label="启用" />
            <el-radio-button label="停用" />
          </el-radio-group>
        </div> -->
        <div class="dialog-footer">
          <el-button size="small" @click="closeModel"> 取消 </el-button>
          <el-button type="primary" size="small" @click="submitFrom">
            确认
          </el-button>
        </div>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script setup>
import { toRefs, reactive, onMounted, computed, ref } from "vue";
import { ArrowDown, Plus } from "@element-plus/icons-vue";
import http from "../libs/http";
import { isKnownSvgAttr } from "@vue/shared";

const state = reactive({
  value: "",
  valueTwo: "",
  mouldVal: "",
  mouldArr: [
    {
      value: "模板1",
      label: "模板1",
    },
    {
      value: "模板2",
      label: "模板2",
    },
    {
      value: "模板3",
      label: "模板3",
    },
  ],
  modelVal: "选择模板",
  tableData: [],
  showModel: false, //显示编辑弹窗
  inputVal: "",
  fileList: [
    {
      name: "food.jpeg",
      url:
        "https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100",
    },
  ],
  dialogImageUrl: "",
  dialogVisible: false,
  picTip: "建议宽高比16:9780*438<尺寸<2560*1440 格式:JPG/JPEG/PNG文件大小≤1000KB",
  radioState: "启用",
  worktype: [],
  vestVal: [],
  siteVest: [],
  listTotal: 0, //总条数
  total_Page: 0, //总页数

  username:'',
  password:'',
  name:'',
  phone:'',
  level: '',
  status: 1,
  uid:''    
});

// 数据初始化
onMounted(() => {
  getUserList(1);
});

// 显示图表逻辑
const search = ref("");
const filterTableData = computed(() =>
  state.tableData.filter(
    (data) =>
      !search.value || data.name.toLowerCase().includes(search.value.toLowerCase())
  )
);
// 编辑
const handleEdit = (index, row) => {
  state.showModel = true;
  console.log(index, JSON.parse(JSON.stringify(row)));
  let newRow = JSON.parse(JSON.stringify(row))
  // 编辑时复现原有数据表格数据
  state.uid = newRow.uid
  let levelSel = newRow.level == 2 ? ["管理员账号"] : newRow.level == 3 ? ["普通账号"] : []
  state.name = newRow.siteName
  state.username = newRow.users
  state.phone = newRow.phone
  state.password = newRow.password
  state.siteVest = levelSel
  state.level = levelSel == "管理员账号" ? 2 : levelSel == "普通账号" ? 3 : []
  state.radioState =  newRow.state
};

// 多选和单选的逻辑
const multipleTableRef = ref();
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  console.log(val, ">>>>>>>>>>>所有选中项");
};

// 分页显示逻辑
const currentPage4 = ref(1);
const pageSize4 = ref(20);
const small = ref(false);
const disabled = ref(false);

const handleSizeChange = (val) => {
  console.log(`${val} items per page`);
};
const handleCurrentChange = (val) => {
  console.log(`current page: ${val}`);
  getUserList(val);
};

// 获取用户账号管理列表
const getUserList = async (pageId) => {
  let param = {
    openid: localStorage.getItem("openid"),
    page: pageId,
  };
  const res = await http.$get("/apies/backend/getUserList", param);
  if (res.code == 200) {
    console.log(">>>>>>>>>>>拿到用户账号列表了", res);
    let userList = res.data.list;
    state.listTotal = res.data.total;
    state.total_Page = res.data.total_page;
    let newUserList = [];
    userList.map((item) => {
      console.log(item.uid);
      newUserList.push({
        uid: item.uid,
        siteName: item.name,
        users: item.username,
        password: item.passwork,
        level: item.level,
        state: item.status == 1 ? "启用" : "停用",
        phone: item.phone
      });
    });
    console.log(newUserList, ">>>>>>>>>>这是新组装的数组");
    state.tableData = newUserList;
  } else {
    console.log(">>>账号列表获取失败!");
  }
};

// 创建账号按钮
const buildUser = () => {
  console.log('>>>>>>>>>>开始创建账号了')
  state.showModel = true;
  state.uid = ""
  clearDate()
}

// 点击表单的取消按钮
const closeModel = () => {
  state.showModel = false;
} 

//获取表单的所有参数
//获取账号类型 1 管理员 2 运营人员
const changeSel = (e) => {
  state.level = e[0] == "管理员账号" ? 2 : e[0] == "普通账号" ? 3 : []
}
//获取账号状态
const changeStaus = (e) => {
  state.status = e == "启用" ? 1 : e == "停用" ? 0 : 1
}

// 正则校验和非空判断
const isInputKong = () => {
  if (state.username == "" || state.password == "" || state.name == "" || state.phone == "" || state.level == "") {
    return false
  } else {
    return true
  }
}
// 每次进入都要清空一下数据
const clearDate = () => {
  state.username = ""
  state.password = ""
  state.name = ""
  state.phone = ""
  state.level = ""
  state.siteVest = []
  state.status = 1
}

//点击表单确认按钮
const submitFrom = async () => {
  if (isInputKong()) {
    let uid = state.uid == "" ? 0 : state.uid
    let param = {
      openid: localStorage.getItem("openid"),
      username: state.username,
      passwork: state.password,
      name: state.name,
      phone: state.phone,
      level: state.level,
      status: state.status,
      uid: uid 
    }
    const res = await http.$post("/apies/backend/createUser", param);
    if (res.code == 200) {
      console.log('>>>>>>>>>>>>>账号创建成功啦啦啦啦啦啦')
      getUserList(1);
      state.showModel = false;
      state.uid == "" ? ElMessage({
        message: '创建成功',
        type: 'success',
      }) : ElMessage({
        message: '编辑成功',
        type: 'success', 
      })
      // 这个要做一下处理，当用户停用是当前正在使用的账号,且表格处于编辑成功的状态，要跳转到登录页面

    } else {
      state.uid == "" ? ElMessage('创建失败！') : ElMessage('编辑失败！')
      state.showModel = false;
    }
  } else {
    ElMessage('填空项不能为空！')
  }
} 


</script>

<style scoped>
.Title {
  font-weight: 600;
  font-size: 20px;
  margin-bottom: 18px;
}

.flewbtn {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.elSelect_a {
  border-radius: 15px;
  width: 250px;
  margin-right: 15px;
}
::v-deep .elSelect_a .el-input__wrapper {
  background-color: #e8e8e8;
  border-color: #c0c4cc;
  box-sizing: border-box;
  box-shadow: none;
}

.elSelect {
  border-radius: 15px;
  width: 250px;
  /* height: 28px; */
  flex: 8;
}
::v-deep .elSelect .el-input__wrapper {
  background-color: #e8e8e8;
  border-color: #c0c4cc;
  box-sizing: border-box;
  box-shadow: none;
}

::v-deep .elSelect .el-input__wrapper:focus {
  background-color: #e8e8e8;
  border-color: #c0c4cc;
  box-sizing: border-box;
  box-shadow: none;
  color: #c0c4cc;
}

::v-deep .elSelect .el-input__inner {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
  box-shadow: none;
  padding: 0;
}

/* 改变输入框样式 */
::v-deep .enterpriseName .el-input__inner {
  /* width:100%; */
  background-color: #e8e8e8;
  border-color: #c0c4cc;
  color: #000;
  padding: 10px;
  box-sizing: border-box;
  /* border-radius: 5px; */
  height: 25px;
  border-radius: 3px;
}

.enterpriseName ::v-deep .el-input__inner {
  border: none;
}

::v-deep .enterpriseName .el-input__wrapper {
  padding: 0;
}

/* 改变上传按钮样式 */
::v-deep.el-upload--picture-card,
::v-deep .el-upload-list__item {
  width: 100px;
  height: 100px;
  line-height: 110px;
  border: none;
  background: #fff;
}

/* 改变选择器样式 */
::v-deep .Selectbox .el-input__wrapper {
  /* width:100%; */
  background-color: #e8e8e8;
  border-color: #c0c4cc;
  color: #000;
  padding: 10px;
  box-sizing: border-box;
  /* border-radius: 5px; */
  height: 28px;
  width: 100% !important;
  flex: 8;
}
::v-deep .Selectbox .el-input__wrapper .el-input__inner {
  border: none;
}
/* 改变文本域样式 */
::v-deep .textTip .el-textarea__inner {
  background-color: #e8e8e8;
  border-color: #c0c4cc;
  color: #000;
  padding: 10px;
  box-sizing: border-box;
}

.block-col-2 .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

/* 隐藏横向滚动条 */
.el-scrollbar__bar {
  display: none !important;
}

#el-id-878-3 .el-dialog__body {
  padding: 0 !important;
}

/* 改变上传框框的大小 */
::v-deep .el-upload--picture-card {
  border: 1px dashed #e7e7e9;
}
::v-deep .el-upload--picture-card:hover {
  border-color: #e7e7e9;
  color: #e7e7e9;
}
::v-deep .el-upload--picture-card {
  width: 70px;
  height: 70px;
  font-size: 16px !important;
}
::v-deep .el-upload {
  width: 70px;
  height: 70px;
  line-height: 50px;
  font-size: 16px;
}
::v-deep .el-upload-list--picture-card .el-upload-list__item {
  width: 70px;
  height: 70px;
  line-height: 50px;
  font-size: 16px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item-actions:hover {
  opacity: 1;
  font-size: 16px;
}

::v-deep .el-upload-list--picture-card .el-upload-list__item-thumbnail {
  width: 70px;
  height: 70px;
  line-height: 50px;
  font-size: 16px;
}
::v-deep .el-upload--picture-card .el-icon-plus {
  width: 28px;
  height: 28px !important;
  line-height: 1.7 !important;
}
::v-deep .avatar {
  width: 70px;
  height: 70px;
}

/* 确认按钮样式 */
.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  margin-top: 90px;
}

::v-deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #409eff !important;
}

.userType {
  font-weight: 600;
  display: flex;
  justify-content: center;
  margin-top: 7px;
  margin-left: 21px;
  margin-right: 17px;
}
.userType_a {
  flex: 8;
  background-color: #e8e8e8;
  padding-left: 6px;
  border-radius: 3px;
  box-sizing: border-box;
}
.carryName {
  line-height: 20px;
  text-align: center;
  font-weight: 600;
  margin-left: 6px;
  margin-right: 17px;
}
.carryName_a {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 18px;
}
.carryName_b {
  /* flex: 2; */
  line-height: 20px;
  text-align: center;
  font-weight: 600;
  margin-left: 33px;
  margin-right: 18px;
}
.bankNum {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 18px;
}
.bankNum_a {
  /* flex: 2; */
  line-height: 20px;
  text-align: center;
  font-weight: 600;
  margin-left: 47px;
  margin-right: 17px;
}
.passW {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 18px;
}
.passW_a {
   /* flex: 2; */
   line-height: 20px;
   text-align: center;
   font-weight: 600;
   margin-left: 47px;
   margin-right: 17px;
}
.passW_b {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 18px;
  margin-bottom: 18px;
}
</style>
